package com.surveillance.validators;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.surveillance.BO.UserBO;
import com.surveillance.entities.User;
import com.surveillance.util.LoadBeans;

@Component
public class AuthValidator implements Validator {

	@Override
	public boolean supports(Class clazz) {
		return User.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		
		User user=(User) target;
		if(user.getLogin().equals("")||user.getPassword().equals("")){
			ValidationUtils.rejectIfEmptyOrWhitespace(errors,"login","required.login");
			ValidationUtils.rejectIfEmptyOrWhitespace(errors,"password","required.login");
		}else{
			UserBO userBO=(UserBO) LoadBeans.getUserBO();
			if(userBO.authenticate(user.getLogin(), user.getPassword())==null){
				errors.rejectValue("password", "user.notFound");
			}
		}
	}

}
